<template>
  <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
    <el-tab-pane label="待审核" name="first">
      <el-form :inline="true" :model="state.dataForm" @keyup.enter="state.getDataList()" style="margin-top: 10px">

        <div class="grid-container">
          <el-form-item label="公司名称">
            <el-input v-model="state.dataForm.companyName" type="text" clearable placeholder="请输入公司名称"
              @change="queryData"></el-input>
          </el-form-item>
        </div>
        <el-table :header-cell-style="{ background: '#eef1f6', color: '#1f2d3d', 'border-color': '#dfe6ec' }"
          v-loading="state.dataListLoading" :data="state.dataList" border
          @selection-change="state.dataListSelectionChangeHandle" style="width: 100%">
          <el-table-column align="center" prop="certifiedId" label="认证编号" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="companyName" label="公司名称" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="brandName" label="品牌名称" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="品牌类型" show-overflow-tooltip>
            <template v-slot="scope">
              <span v-if="scope.row.brandType === '1'">自有品牌</span>
              <span v-else-if="scope.row.brandType === '2'">代理品牌</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="brandClassName" label="产地" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="saleRegion" label="可售区域" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="createAt" label="认证申请时间" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="auditor" label="审核人" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="auditTime" label="审核时间" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="审核状态" show-overflow-tooltip>
            <template v-slot="scope">
              <span v-if="scope.row.status === '0'" style="color: #f56c6c">待审核</span>
              <span v-else-if="scope.row.status === '1'" style="color: #67c23a">已通过</span>
              <span v-else-if="scope.row.status === '2'" style="color: #f56c6c">已驳回</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="驳回原因" show-overflow-tooltip>
            <template v-slot="scope">
              <span v-if="scope.row.status !== '1'">{{ scope.row.rejectReason || '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" align="center" prop="readOnly" label="操作">
            <template v-slot="scope">
              <!-- 列表按钮 -->
              <el-button link @click="handleView(scope.row)" style="color: rgba(22, 119, 255, 1)">查看</el-button>
              <el-button v-if="scope.row.status === '0'" link @click="handleAudit(scope.row)"
                style="color: rgba(22, 119, 255, 1)">审核</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <el-pagination :current-page="state.page" :page-sizes="[10, 20, 50, 100]" :page-size="state.limit"
        :total="state.total" layout="total, sizes, prev, pager, next, jumper" @size-change="state.pageSizeChangeHandle"
        @current-change="state.pageCurrentChangeHandle"> </el-pagination>
      <!-- <BrandViewDialog ref="viewDialogRef" @success="state.getDataList()" /> -->
    </el-tab-pane>
    <el-tab-pane label="全部" name="second">
      <el-form :inline="true" :model="state.dataForm" @keyup.enter="state.getDataList()" style="margin-top: 10px">

        <div class="grid-container">
          <el-form-item label="公司名称">
            <el-input v-model="state.dataForm.companyName" type="text" clearable placeholder="请输入公司名称"
              @change="queryData"></el-input>
          </el-form-item>

          <el-form-item label="状态">
            <el-select v-model="state.dataForm.status" placeholder="请选择审核状态" clearable @change="queryData">
              <el-option label="待审核" value="0"></el-option>
              <el-option label="审核通过" value="1"></el-option>
              <el-option label="审核驳回" value="2"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-table :header-cell-style="{ background: '#eef1f6', color: '#1f2d3d', 'border-color': '#dfe6ec' }"
          v-loading="state.dataListLoading" :data="state.dataList" border
          @selection-change="state.dataListSelectionChangeHandle" style="width: 100%">
          <el-table-column align="center" prop="certifiedId" label="认证编号" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="companyName" label="公司名称" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="brandName" label="品牌名称" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="品牌类型" show-overflow-tooltip>
            <template v-slot="scope">
              <span v-if="scope.row.brandType === '1'">自有品牌</span>
              <span v-else-if="scope.row.brandType === '2'">代理品牌</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="brandClassName" label="产地" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="saleRegion" label="可售区域" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="createAt" label="认证申请时间" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="auditor" label="审核人" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="auditTime" label="审核时间" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="审核状态" show-overflow-tooltip>
            <template v-slot="scope">
              <span v-if="scope.row.status === '0'" style="color: #f56c6c">待审核</span>
              <span v-else-if="scope.row.status === '1'" style="color: #67c23a">已通过</span>
              <span v-else-if="scope.row.status === '2'" style="color: #f56c6c">已驳回</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="驳回原因" show-overflow-tooltip>
            <template v-slot="scope">
              <span v-if="scope.row.status !== '1'">{{ scope.row.rejectReason || '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" align="center" prop="readOnly" label="操作">
            <template v-slot="scope">
              <!-- 列表按钮 -->
              <el-button link @click="handleView(scope.row)" style="color: rgba(22, 119, 255, 1)">查看</el-button>
              <el-button v-if="scope.row.status === '0'" link @click="handleAudit(scope.row)"
                style="color: rgba(22, 119, 255, 1)">审核</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <el-pagination :current-page="state.page" :page-sizes="[10, 20, 50, 100]" :page-size="state.limit"
        :total="state.total" layout="total, sizes, prev, pager, next, jumper" @size-change="state.pageSizeChangeHandle"
        @current-change="state.pageCurrentChangeHandle"> </el-pagination>
      <!-- <BrandViewDialog ref="viewDialogRef" @success="state.getDataList()" /> -->
    </el-tab-pane>
    <BrandViewDialog ref="viewDialogRef" @success="state.getDataList()" />

  </el-tabs>

</template>
<script lang="ts" setup>
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import useView from "@/hooks/useView";
import { nextTick, reactive, ref, toRefs, onMounted } from "vue";
import router from "@/router";
import BrandViewDialog from "@/components/BrandViewDialog.vue";

import type { TabsPaneContext } from 'element-plus'

const activeName = ref('first')

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
  // 根据标签页切换时重置查询条件并获取数据
  if (tab.props.name === 'first') {
    // 待审核标签页
    state.dataForm.status = '0'
    state.page = 1
    state.getDataList()
  } else if (tab.props.name === 'second') {
    // 全部标签页
    state.dataForm.status = ''
    state.page = 1
    state.getDataList()
  }
}

const view = reactive({
  getDataListURL: "/noc/authbrandaudit/list",
  getDataListIsPage: true,
  dataForm: {
    companyName: "",
    status: ""
  }
});
// 分类选项
const classOptions = ref<any[]>([]);
// 选中的分类路径
const selectedClassPath = ref<string[]>([]);
// 状态多选值
const selectedStatus = ref([]);

//获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case "0":
      return "待审核";
    case "1":
      return "已通过";
    case "2":
      return "已驳回";
    default:
      return "";
  }
};

//获取状态样式
const getStatusClass = (status: string) => {
  switch (status) {
    case "0":
      return "el-tag--info";
    case "1":
      return "el-tag--success";
    case "2":
      return "el-tag--danger";
    default:
      return "";
  }
};

//处理搜索
const handleSearch = () => {
  state.page = 1; // 重置页码到第一页
  state.getDataList();
};

//处理分页
const handlePage = (page: number) => {
  state.page = page;
};

// 修改查询按钮的点击处理
const queryData = () => {
  saveCurrentQuery();
  state.page = 1; // 重置页码到第一页
  // 根据当前标签页设置状态过滤
  if (activeName.value === 'first') {
    state.dataForm.status = '0'
  }
  state.getDataList();
};

// 修改重置方法以清除保存的查询条件
const resetForm = () => {
  view.dataForm.companyName = "";
  // 根据当前标签页设置状态
  if (activeName.value === 'first') {
    view.dataForm.status = "0";
  } else {
    view.dataForm.status = "";
  }
  // 重置状态多选值
  selectedStatus.value = [];
  // 重置级联选择器的值
  selectedClassPath.value = [];
  // 清除保存的查询条件
  state.page = 1; // 重置页码到第一页
  state.getDataList();
};

// 在执行查询前保存当前查询条件
const saveCurrentQuery = () => {
  const query = {
    dataForm: { ...state.dataForm },
    selectedStatus: [...selectedStatus.value],
    selectedClassPath: [...selectedClassPath.value]
  };
  sessionStorage.setItem("nocproductListQuery", JSON.stringify(query));
};

// 在 onMounted 中添加
const route = useRoute();
onMounted(() => {
  // getClassList();

  // 检查是否是从编辑页面返回
  if (route.query.fromEdit === "true") {
    // 从编辑页面返回，恢复查询条件
    const savedQuery = sessionStorage.getItem("nocproductListQuery");
    if (savedQuery) {
      try {
        const query = JSON.parse(savedQuery);
        Object.assign(state.dataForm, query.dataForm);
        selectedStatus.value = query.selectedStatus || [];
        selectedClassPath.value = query.selectedClassPath || [];
      } catch (e) {
        console.error("解析查询条件失败", e);
      }
    }
  }

  // 初始化时根据当前标签页设置状态
  if (activeName.value === 'first') {
    state.dataForm.status = '0'
  }

  state.getDataList();
});
// 跳转新增产品系列页面
const addOrUpdateHandle = () => {
  saveCurrentQuery(); // 保存当前查询条件
  router.push({
    path: "/program/nocorder-add",
    query: {
      from: "/program/nocorder-list"
    }
  });
};
const viewDialogRef = ref<InstanceType<typeof BrandViewDialog>>();
// 跳转查看页面
const handleView = (row: any) => viewDialogRef.value?.open(row, "view");
const handleAudit = (row: any) => viewDialogRef.value?.open(row, "audit");

const state = reactive({ ...useView(view), ...toRefs(view) });
state.limit = 20;
// 加载分类和品牌数据
onMounted(() => {
  // getClassList();
  console.log("获取到的数据:", state.dataList);
});
</script>
<style lang="scss" scoped>
::v-deep .el-table .cell {
  white-space: nowrap;
}

.el-input {
  width: 218px;
  height: 32px;
  opacity: 1;
  border-radius: 5px;
  background: rgba(255, 255, 255, 1);
}

.form {
  display: flex;
  justify-content: space-between;
}

.grid-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: left;
  // grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  /* 自动适应列宽，每列至少200px */
  gap: 16px;
  /* 元素间距 */
}

.demo-tabs>.el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>
